/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text,
    useTheme,
    Container,
    Button,
    IconArrowRight,
    Input,
    Select,
    CheckSwitch,
    LineColumn,
    SuffixInput,
    InputLine,
    InputDatalist,
    CommitInput,
    TextArea,
    ButtonRefComp,
    IconButton,
    IconZapOff,
    IconCheckSquare,
    ListFlexRow,
    Itext,
    IconCoffee,
    InputPure
} from "customize-easy-ui-component";
//InputDatalist 替换 ComboBoxDatalist；
import {useContext, } from "react";
import useFlowToMutation from "../hook/useFlowRequestMutation";
import {OneUserChoose} from "../../common/user/OneUserChoose";
import RoutingContext from "../../routing/RoutingContext";
import UserContext from "../../routing/UserContext";
import {Link as RouterLink} from "../../routing/Link";

export const 延期理由s=["已检正在出具检验报告","已约定检验时间","已上报监察机构","手工报告单上报监察机构","正在确认未检原因","设备状态已变更未提交变更申请",
    "因保温层未拆除或流动式起重机无法实施检验","备用锅炉或季节性使用锅炉","其它"];
export const 取消理由s=["任务生成错误","客户申请撤销","协议取消","其它"];

interface Props {
    readOnly?: boolean;
    editable?: boolean;
    req?:any;
    mutationFunc: (...args: any[]) => any;
    curFlow?:any;
}
/**两种任务异常 申请单复合组件： 1，延期 ，2，消除任务  处置申请。
 * 都是一关卡审核模式：
 * */
export const TaskExceptionDeal: React.FunctionComponent<Props> = (
    {
       readOnly,
       editable,
       req=null,    //【只读的】:从好几代祖先前的DetailedGuide在graphQL获得后端服务器数据层层传递下来的。
      mutationFunc,
        curFlow,
     }) =>
{
  //这个位置就应该体现解析graphQL内省的json集合字段：data:{}从string变身对象。
    const theme = useTheme();
    const { history } = useContext(RoutingContext);
    const {save, field, reurl}= window.history.state?.state??{};      //通用伪对话框传递格式:多选设备返回对象
    //假如从多选选定设备页面返回的："移出多选集" : "加入多选集" 操作过后，将会导致save.devs[]对象变身成了设备页面的经过SessionStorage倒腾一手的对象。
    const edt = save?  save : req;
    //若从save恢复的，confirm已经解析为对象Object:
    let  dat = edt?.dat instanceof Object?  edt?.dat : JSON.parse(edt?.dat || '{}');
    const [理由, set理由] = React.useState(dat?.理由);
    const [到期日, set到期日] = React.useState(dat?.到期日);

  //   const curFlow=sessionStorage['审批单']&&JSON.parse(sessionStorage['审批单']);
    const {call:flowToFunc,doing:flowing, called:flowed, reset:flowreset}=useFlowToMutation();
    //第二关批准人，或者唯一关的审核人； 语义上问题：若2关口的话那么打印发放人员反而是通常意义的最终核准人了, 别扭，通用申请单想要统一语义？通用申请单过滤统计用处不大?。
    const [auditor, setAuditor] = React.useState<any>(req?.auditor);
    const [director, setDirector] = React.useState<any>(req?.director);
    //有2关审批的算是第1关的审核人；
    const [manager, setManager] = React.useState<any>(req?.manager);
    const {user} = useContext(UserContext);
    const  audat = JSON.parse(edt?.audat || '{}');
    const [memo, setMemo] = React.useState<string|undefined>(audat?.memo);
    const  drdat = JSON.parse(edt?.drdat || '{}');
    const [drmemo, setDrmemo] = React.useState<string|undefined>(drdat?.memo);
    const  mndat = JSON.parse(edt?.mndat || '{}');
    const [mnmemo, setMnmemo] = React.useState<string|undefined>(mndat?.memo);
    const floUrl='/request/'+ req?.id;
    const commitBlurRef =React.useRef<HTMLDivElement | null>(null);
    //为了修改可以在React页面立刻同步显示需要的，不能直接修改原数组对象。 腾挪dat?.devs到了ispdvs：受编辑器控制的
    //不需要0所以下面的<InputPure type="number" value={ fseq || ''}，若要0取值的要改成value={ fseq || '0'}才能显示为0的。
    //【注意】Select组件必须加上<option></option>否则默认第一条,后端可能根本就没有数据 也显示默认第一条。
    //【关键】字段：在首次发起流程或者退回到编制申请重新提交时刻，send取值决定了BPMN的审批是2层的还是1层审批人的。
    const send='线上告知';
    async function confirmation() {
        //后端生成，前端编辑器却没有保存的字段，透明传递给通知书的。
        // const{使用单, 服务单, 设备种}= dat;
        //后端最开始就已经初始化的 也要一起打包dat{JSON}回传 ?前端篡改 何意义?
        const newdat={
            dat: {
                理由, taskId: dat?.taskId,  到期日,
            },
        };
        //伪对话框跳转恢复也会用到的。
        return newdat;
    }

  return (
    <div
      css={{
        [theme.mediaQueries.md]: {
          height: "auto",
          display: "block"
        }
      }}
    >
      <Text
        css={{
          flex: 1,
          textAlign: "center",
          [theme.mediaQueries.md]: {
            textAlign: "left"
          }
        }}
        wrap={true}
        variant="h5"
        gutter={false}
      >
        审批通过后，可{req?.mod==='taskDelay'? '消除任务的异常情况':'取消该任务'}。
          {req?.mod==='cancelTask' && '任务下的某个检验若已经有报告的，请提前清理关联报告，避免无法成功取消任务。'}
      </Text>

      <div
        css={{
          flex: 1,
          [theme.mediaQueries.md]: {
            flex: "none"
          }
        }}
      >
        <div>
          <Container>
            <div
              css={{
                paddingTop: theme.spaces.lg,
                paddingBottom: theme.spaces.lg
              }}
            >
                <Text variant="h6">第一步，提交材料:</Text>
                <Text>有关该任务设备清单,请跳回任务页面：</Text>
                <LineColumn column={3}>
                    <InputLine label={`任务链接:`}>
                        <RouterLink href={"/task/"+dat?.taskId}>
                            <Text>/task/{dat?.taskId}</Text>
                        </RouterLink>
                    </InputLine>
                    { req?.mod==='taskDelay'?
                        <InputLine label={`延期原因(选):`}>
                            <InputDatalist value={ 理由 || ''} datalist={延期理由s}
                                           onListChange={v => set理由(v ||undefined)} />
                        </InputLine>
                        :
                        <InputLine label={`取消原因(选):`}>
                            <InputDatalist value={ 理由 || ''} datalist={取消理由s}
                                           onListChange={v => set理由(v ||undefined)} />
                        </InputLine>
                    }
                    {req?.mod==='taskDelay' &&
                        <InputLine label={`延期后任务到期日:`}>
                            <Input type='date'  value={ 到期日  || ''}
                                   onChange={e => set到期日( e.currentTarget.value||undefined ) } />
                        </InputLine>
                    }

                    <InputLine label={`更详细原因(录入):`}>
                        <TextArea required rows={4}
                                  value={理由} onChange={e => set理由( e.currentTarget.value||undefined ) }
                        />
                    </InputLine>
                 </LineColumn>

                {
                    (req?.status==='INIT') &&
                      <Button size="lg" intent="primary"  iconAfter={<IconArrowRight />}
                              css={{ marginTop: theme.spaces.sm, whiteSpace:'unset' }}
                              disabled={req?.status !== 'INIT'}
                        onPress={ async () => {
                          const sendInp=await confirmation();
                          const inpPreare={ ...sendInp,
                              dat: JSON.stringify({...sendInp.dat}),
                          };
                          await mutationFunc(req?.id, 'UPD', inpPreare);
                        } }
                      > 先保存申请资料
                      </Button>
                }
            </div>

              <InputLine label={(req?.mod==='taskDelay'? '任务延期':'取消任务') +'的审核人:'}>
                  { (req?.status==='INIT') ?
                      <OneUserChoose name={auditor?.person?.name!} setEditorVar={setAuditor}
                                 oobj={auditor}/>
                      :
                      <Text css={{textAlign: "left"}}>{auditor?.person?.name}</Text>
                  }
              </InputLine>

              { (req?.status==='INIT' || (curFlow && curFlow?.entId === req?.id && curFlow?.tdId==='request_author_modify') ) &&
                  <Button intent="primary" disabled={(curFlow && !(curFlow?.entId === req?.id) && req?.status!=='INIT') ||
                         ( !auditor ) }
                        onPress={async () => {
                             await flowToFunc(curFlow?.utId, req?.id,3,"", "YES",(req?.mod==='taskDelay'? '任务延期':"取消任务")+'申请:'+user?.person?.name,
                                  auditor?.id, floUrl, 20);
                              sessionStorage['审批单'] = null;
                              history.push(`/zeebeTodo`);
                        }}
                  >
                      { ((curFlow?.tdId==='request_author_modify')? '再提交申请' : '提交申请给审核人') }
                  </Button>
              }

              <Text variant="h6">第二步，审核人的审核情况：</Text>
              {  ((curFlow && curFlow?.entId === req?.id) || req?.status!=='INIT') &&
                  <InputLine label={`审核人的意见:`}>
                      { ((curFlow?.tdId==='request_auditor_opinion' && send==='线上告知') || curFlow?.tdId==='request_manager_opinion') ?
                          <>
                          { send==='线上告知'?
                              <CommitInput  value={ memo || ''}  onSave={txt => setMemo( txt || undefined) }
                                            placeholder="如果拒绝或回退的，请给出理由"
                              />
                              :
                              <CommitInput  value={ mnmemo || ''}  onSave={txt => setMnmemo( txt || undefined) }
                                            placeholder="如果拒绝或回退的，请给出理由"
                              />
                          }
                          </>
                          :
                          <Text css={{textAlign: "left"}}>{send==='线上告知'? memo : mnmemo}</Text>
                      }
                  </InputLine>
              }
              {send!=='线上告知' &&
                  <InputLine label='打印和发放人员:'>
                      { curFlow?.tdId==='request_manager_opinion' ?
                          <OneUserChoose name={auditor?.person?.name!} setEditorVar={setAuditor}
                                         oobj={auditor}/>
                          :
                          <Text css={{textAlign: "left"}}>{auditor?.person?.name}</Text>
                      }
                  </InputLine>
              }

              { (curFlow?.entId === req?.id && (curFlow?.tdId==='request_auditor_opinion' ) ) &&
                  <>
                      <Button intent="primary" disabled={curFlow && !(curFlow?.entId === req?.id)}
                              onPress={async () => {
                                  const opndat= req?.status==='INIT' ? '' :
                                      JSON.stringify( {memo} );
                                  await flowToFunc(curFlow?.utId, req?.id,3,opndat, "YES",":"+user?.person?.name,
                                      null , null, 15);
                                  sessionStorage['审批单'] = null;
                                  history.push(`/zeebeTodo`);
                              }}
                      >
                      {  '通过的允许'+ (req?.mod==='taskDelay'? '延期':"取消")  }
                      </Button>
                      {
                          (req?.status!=='INIT') &&
                          <>
                              <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                      disabled={curFlow && !(curFlow?.entId === req?.id)}
                                      onPress={async () => {
                                          const opndat=JSON.stringify( {memo} );
                                          await flowToFunc(curFlow?.utId, req?.id,3,opndat, "NO",":"+user?.person?.name,
                                              auditor?.id, null, 20);
                                          sessionStorage['审批单'] = null;
                                          history.push(`/zeebeTodo`);
                                      }}
                              >
                                  { '审批不通过' }
                              </Button>
                              <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                      disabled={curFlow && !(curFlow?.entId === req?.id)}
                                      onPress={async () => {
                                          const opndat=JSON.stringify( {memo} );
                                          await flowToFunc(curFlow?.utId, req?.id,3,opndat, "BACK",":"+user?.person?.name,
                                              auditor?.id, null, 20);
                                          sessionStorage['审批单'] = null;
                                          history.push(`/zeebeTodo`);
                                      }}
                              >
                                  { '退回' }
                              </Button>
                          </>
                      }
                  </>
              }

            { (curFlow?.entId === req?.id && (curFlow?.tdId==='request_deny' || curFlow?.tdId==='request_finish')) &&
                <>
              <Button intent="primary" disabled={curFlow && !(curFlow?.entId === req?.id)}
                      onPress={async () => {
                          await flowToFunc(curFlow?.utId, req?.id,1,'', "YES");
                          sessionStorage['审批单'] = null;
                          history.push(`/zeebeTodo`);
                      }}
              >
                {'知道了'}
              </Button>
                </>
            }

          { req?.status==='END' &&
                '恭喜，已经处理完结'
          }
          </Container>
        </div>
      </div>

    </div>
  );
};

